package fhv.at.imageprocessing.saveImage;

import java.io.Serializable;

import javax.media.jai.PlanarImage;

import fhv.at.imageprocessing.ImageChangedEvent;
import fhv.at.imageprocessing.ImageChangedListener;
import fhv.at.imageprocessing.ImageHelper;
import fhv.at.imageprocessing.ImageNeededEvent;
import fhv.at.imageprocessing.ImageProcessor;

/**
 * Save image bean. Saves the new image to disk
 * 
 * @author phru
 * 
 */
public class SaveImage implements ImageChangedListener, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String imagePath = "images/newImage.jpg";
	private String imageType = "JPEG";
	private final ImageHelper imageHelper;
	private PlanarImage planarImage;

	public SaveImage() {
		int maxParents = 1;
		imageHelper = new ImageHelper(maxParents, this);
	}

	public String getImagePath() {
		return imagePath;
	}

	public void setImagePath(String imagePath) {
		this.imagePath = imagePath;
		imageHelper.fireImageNeededEvent();
	}

	public String getImageType() {
		return imageType;
	}

	public void setImageType(String imageType) {
		this.imageType = imageType;
	}

	/* Eigentliche Bildbearbeitung */
	@Override
	public void manipulateImage() {
		if (planarImage != null) {
			if (imagePath != null) {
				if (imageType != null) {
					ImageProcessor ip = ImageProcessor.getInstance();
					ip.saveImage(planarImage, imagePath, imageType);
					imageHelper.fireImageChangedEvent();
				}
			}
		}
	}

	/* Implementation fur Eventregistrierung */
	@Override
	public void addImageChangedListener(ImageChangedListener icl) {
		imageHelper.addImageChangedListener(icl);
	}

	@Override
	public void removeImageChangedListener(ImageChangedListener icl) {
		imageHelper.removeImageChangedListener(icl);
	}

	@Override
	public void addImageNeededListener(ImageChangedListener icl) {
		imageHelper.addImageNeededListener(icl);
	}

	@Override
	public void removeImageNeededListener(ImageChangedListener icl) {
		imageHelper.removeImageNeededListener(icl);
	}

	/* Implementation fur ImageChangedListener */
	@Override
	public void imageValueChanged(ImageChangedEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageValueChanged");
		planarImage = imageHelper.getPlanarImage(ice);
		manipulateImage();
	}

	@Override
	public void imageNeeded(ImageNeededEvent ice) {
		System.out.println(getClass().getSimpleName() + " imageNeeded");
		imageHelper.fireImageChangedEvent();
		// imageHelper.fireImageChangedEvent(ice);
	}

	@Override
	public ImageChangedListener getRefFromSource() {
		return this;
	}

	@Override
	public PlanarImage getPlanarImage() {
		return planarImage;
	}

}
